<template>
  <div class="container" ref="mainCon">
    <div class="mainCon" style="padding-bottom: 0">
      <el-row
        v-if="loginType === 'JC'"
        class="toolbar searchInputWidth"
        style="padding-bottom: 0"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="单位名称" class="row-padding-bottom">
              <el-input
                type="text"
                placeholder="名称或统一社会信用代码"
                v-model="filterField.keyword"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6" v-if="!isEsUser()">
            <el-form-item label="动态信用等级" class="row-padding-bottom">
              <el-select
                v-model="filterField.gradeLevel"
                filterable
                placeholder="请选择"
                no-data-text="请选择"
                clearable
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="(item, index) in selectLevel"
                  :key="index"
                  :label="item.name"
                  :value="item.gradeLevel"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6" v-if="isEsUser()">
            <el-form-item label="单位角色" class="row-padding-bottom">
              <el-select
                v-model="filterField.type"
                filterable
                placeholder="请选择"
                clearable
                @change="changeType"
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="(item, index) in scoreDimTypeArr"
                  :key="index"
                  :label="item.scoreDimTypeDesc"
                  :value="item.scoreDimType"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced && isEsUser()">
            <el-col :lg="8" :xl="6">
              <el-form-item label="动态信用等级" class="row-padding-bottom">
                <el-select
                  v-model="filterField.gradeLevel"
                  filterable
                  placeholder="请选择"
                  :no-data-text="isEsUser() ? '请先选择单位角色' : '请选择'"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="(item, index) in selectLevel"
                    :key="index"
                    :label="item.name"
                    :value="item.gradeLevel"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item
                v-if="isEsUser()"
                label="项目名称"
                class="row-padding-bottom"
              >
                <el-input
                  type="text"
                  placeholder="请输入项目名称"
                  v-model="filterField.projectName"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- <el-form-item>
                    <el-button
                        type="primary"
                        icon="icon iconfont iconchazhao1"
                        @click="searchList"
                        class="commonBtn"
                    ></el-button>
                </el-form-item> -->
          </template>
          <el-col :lg="8" :xl="6">
            <el-form-item label="">
              <a
                @click="toggleAdvanced"
                style="margin-left: 40px; color: #409eff; cursor: pointer"
                class="btnColor"
                v-if="isEsUser()"
              >
                {{ advanced ? '收起' : '展开' }}
                <i
                  :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                ></i>
              </a>
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="searchBtn"
              >
                <span>搜索</span>
              </el-button>
            </el-form-item>
            <el-form-item>
              <exportBtn
                :dataLen="tableList.length"
                :filterField="filterField"
                :api="api"
              ></exportBtn>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row v-else class="toolbar searchInputWidth" style="padding-bottom: 0">
        <exportBtn
          :dataLen="tableList.length"
          :filterField="filterField"
          :api="api"
        ></exportBtn>
      </el-row>
      <div class="spacing" v-if="loginType === 'JC'"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          @sort-change="sortChange"
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column prop="projectName" label="单位名称" min-width="200">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeDesc"
            label="单位角色"
            align="center"
            :formatter="formatTd"
            min-width="100"
          ></el-table-column>
          <el-table-column
            prop="uscc"
            label="统一社会信用代码"
            align="center"
            :formatter="formatTd"
            min-width="200"
          ></el-table-column>
          <el-table-column
            label="参评项目个数"
            align="center"
            :formatter="formatTd"
            :sortable="loginType === 'JC' ? 'custom' : false"
            min-width="180"
            prop="projectCount"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-if="scope.row.projectCount && isShowDetail"
                @click="toProjectList(scope.row)"
                >{{ scope.row.projectCount }}</el-link
              >
              <span v-else>0</span>
            </template>
          </el-table-column>
          <!-- 黄石定制需求-start -->
          <el-table-column
            prop="companyAvgScore"
            label="月度平均信用分数"
            align="center"
            :formatter="formatTd"
            min-width="200"
            v-if="isHsUser()"
            key="1"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.companyAvgScore">
                {{ scope.row.companyAvgScore }}
              </span>
              <span v-else>尚未生成</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="score"
            label="月度平均信用等级"
            align="center"
            :formatter="formatTd"
            min-width="160"
            v-if="isHsUser()"
            key="2"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.companyAvgGradeLevel">
                {{ scope.row.companyAvgGradeLevel }}
              </span>
              <span v-else>尚未生成</span>
            </template>
          </el-table-column>
          <!-- 黄石定制需求-end -->
          <el-table-column
            prop="score"
            label="动态信用分数"
            align="center"
            :formatter="formatTd"
            min-width="140"
            :sortable="loginType === 'JC' ? 'custom' : false"
            v-if="!isHsUser()"
            key="3"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.projectCount">
                {{ scope.row.score }}
              </span>
              <span v-else>- -</span>
            </template>
          </el-table-column>
          <el-table-column
            label="动态信用等级"
            align="center"
            :formatter="formatTd"
            min-width="120"
            v-if="!isHsUser()"
            key="4"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.projectCount">
                {{
                  scope.row.gradeLevel === 'O' ? '其他' : scope.row.gradeLevel
                }}
              </span>
              <span v-else>- -</span>
            </template>
          </el-table-column>
          <!-- 信用历史评价 -->
          <el-table-column
            label="操作"
            align="left"
            fixed="right"
            :formatter="formatTd"
            width="160"
          >
            <template slot-scope="scope">
              <el-link type="primary" @click="toHistoryList(scope.row)"
                >查看历史评价</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无企业评级相关数据"></emptyTable>
          </div>
        </el-table>

        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          v-if="loginType === 'JC'"
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
  </div>
</template>

<script>
import emptyTable from '@/components/publicCom/emptyTable'
import Pagination from '@/components/publicCom/pagination'
// import scrollTable from '@/mixin/scrollTable.js';

export default {
  name: 'scoreTable',
  // mixins:[scrollTable],
  components: {
    emptyTable,
    Pagination,
  },
  props: {
    scoreDimType: {
      type: String,
      default: '',
    },
    isIndex: {
      type: String,
      default: '',
    },
  },
  watch: {
    scoreDimType(newValue, oldValue) {
      this.getLevelList(this.scoreDimType)
      if (this.$store.state.userType === 'COMPANY') {
        this.getCompanyList(this.scoreDimType)
      } else {
        this.filterField.type = newValue
        this.filterField.keyword = ''
        this.filterField.gradeLevel = ''
        this.$nextTick(function () {
          this.$refs.pagination.getTableListData()
        })
      }
    },
    isIndex(newValue, oldValue) {
      this.getApi()
    },
  },
  data() {
    return {
      hiddleToolBar: false,
      tableHeight: null,
      advanced: false,
      scoreDimTypeArr: [
        {
          scoreDimType: '0',
          scoreDimTypeDesc: '建设单位',
        },
        {
          scoreDimType: '5',
          scoreDimTypeDesc: '施工单位',
        },
        {
          scoreDimType: '10',
          scoreDimTypeDesc: '分包单位',
        },
      ],
      loginType: '',
      selectLevel: [],
      //表格数据
      tableList: [],
      requestUrl:
        '/api-ps/creditCompanyScore/expand/getCompanyScoreListByMonitor',
      //搜索条件
      filterField: {
        keyword: '',
        gradeLevel: '',
        type: '',
        projectName: '',
      },
      isShow: false, //列表加载
      loading: false,
      isShowDetail: '',
      api: '',
    }
  },
  created() {
    if (!this.isEsUser()) {
      this.filterField.type = this.scoreDimType
      this.getLevelList(this.scoreDimType)
    }
    this.loginType = 'JC'
    //PROJECT_OWNER  业主项目管理用户
    if (
      this.$store.state.userType === 'COMPANY' ||
      this.$store.state.userType == 'PROJECT_OWNER'
    ) {
      this.loginType = 'QY'
      this.getCompanyList(this.scoreDimType)
    } else {
      this.$nextTick(function () {
        this.$refs.pagination.getTableListData()
      })
    }
    this.getApi()
    this.isShowDetail =
      this.$store.state.buttonLimitsArr.indexOf('scoreList:detail') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('scoreListSGF:detail') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('scoreListJSF:detail') > -1
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleScroll(e) {
      this.$nextTick(function () {
        //变量scrollTop是滚动条滚动时，距离顶部的距离
        var scrollTop = e.target.scrollTop
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          this.tableHeight = window.innerHeight - 240
          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    // 选择角色
    changeType(val) {
      this.filterField.gradeLevel = ''
      if (val) {
        this.getLevelList(this.filterField.type)
      } else {
        this.selectLevel = []
        // this.$message({
        //     type: "error",
        //     message: "请先选择单位角色！",
        // });
      }
    },
    // 获取评级配置
    getLevelList(type) {
      return this.axios({
        method: 'post',
        url: 'api-ps/creditLevel/expand/getCreditLevelList',
        data: {
          type,
        },
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            const results = response.data.result
            results.forEach((v) => {
              v.name = v.gradeLevel
            })
            this.selectLevel = results
            const otherLevel = { gradeLevel: 'O', name: '其他' }
            this.selectLevel.push(otherLevel)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    // 企业端企业列表
    getCompanyList(type) {
      return this.axios({
        method: 'post',
        url: '/api-ps/creditCompanyScore/expand/getCompanyScoreByCompany',
        data: {
          type,
        },
      })
        .then((response) => {
          if (response.data.hasError) {
            this.$message.error(response.data.errorMsg)
          } else {
            const results = response.data.result
            this.tableList = results
            if (this.tableList.length < 1) {
              this.isShow = true
            }
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    toProjectList(row) {
      this.$router.push({
        path: '/home/enterpriseScore/scoreProjectList',
        name: 'scoreProjectList',
        query: {
          uscc: row.uscc,
          type: row.type,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/enterpriseScore/scoreList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 监察企业端历史评价
    toHistoryList(row) {
      this.$router.push({
        path: '/home/enterpriseScore/enterpriseHistoryScoreList',
        name: 'enterpriseHistoryScoreList',
        query: {
          uscc: row.uscc,
          type: row.type,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/enterpriseScore/scoreList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getApi() {
      let loginType = localStorage.getItem('loginType')
      if (loginType === 'JC') {
        //0 建设单位;1 施工单位, 2 分包单位
        if (this.isIndex == 0) {
          this.api = 'api-s/report/export_JC_CS_COMPANY_SCORE_BUILD'
        } else if (this.isIndex == 1) {
          this.api = 'api-s/report/export_JC_CS_COMPANY_SCORE_CONSTRUCTION'
        } else if (this.isIndex == 2) {
          this.api = 'api-s/report/export_JC_CS_COMPANY_SCORE_SUBCONTRAC'
        }
      } else {
        if (this.isIndex == 0) {
          this.api = 'api-s/report/export_QY_COMPANY_SCORE_BUILD'
        } else if (this.isIndex == 1) {
          this.api = 'api-s/report/export_QY_COMPANY_SCORE_CONSTRUCTION'
        } else if (this.isIndex == 2) {
          this.api = 'api-s/report/export_QY_COMPANY_SCORE_SUBCONTRAC'
        }
      }
    },
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 40 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #333333;
}
.wideInput {
  /deep/ .el-input__inner {
    width: 270px !important;
  }
}
@import '../../../static/css/filterArea.less';
</style>
